<template>
	<!-- 图表查看 -->
	<view class="charts">
		<view class="charts-view-list" v-if="index == 1"> <!-- 防火检查记录 -->
			<view class="uni-list">
				<view class="charts-view-time-ops">
					<view class="charts-view-time-ops-son">
						<view>
							<u-button size="mini" @click="showOpsUnit" shape="circle">选择单位：{{unit[0]}}</u-button>
						</view>
						<view>
							<u-picker @cancel="onClosePicker" @confirm="onPickerConfirm" @change="changePickerHandler"
								:show="showPicker" :columns="unitNames"></u-picker>
						</view>
					</view>
					<view class="charts-view-time-ops-content">
						<qiun-data-charts type="column" :opts="opts" :chartData="chartData" @getIndex="getIndex" />
					</view>
				</view>
			</view>
		</view>
	</view>
	<view class="charts">
		<view class="charts-view-list" v-if="index == 2"> <!-- 防火检查记录 -->
			<view class="uni-list">
				<view class="charts-view-time-ops">
					<view class="charts-view-time-ops-son">
						<view>
							<u-button size="mini" @click="showOpsUnit" shape="circle">选择单位：{{unit[0]}}</u-button>
						</view>
						<view>
							<u-picker @cancel="onClosePicker" @confirm="onPickerConfirm" @change="changePickerHandler"
								:show="showPicker" :columns="unitNames"></u-picker>
						</view>
					</view>
					<view class="charts-view-time-ops-content">
						<qiun-data-charts type="column" :opts="opts" :chartData="chartData" @getIndex="getIndex" />
					</view>
				</view>
			</view>
		</view>
	</view>
	<view class="charts">
		<view class="charts-view-list" v-if="index == 3"> <!-- 防火检查记录 -->
			<view class="uni-list">
				<view class="charts-view-time-ops">
					<view class="charts-view-time-ops-son">
						<view>
							<u-button size="mini" @click="showOpsUnit" shape="circle">选择单位：{{unit[0]}}</u-button>
						</view>
						<view>
							<u-picker @cancel="onClosePicker" @confirm="onPickerConfirm" @change="changePickerHandler"
								:show="showPicker" :columns="unitNames"></u-picker>
						</view>
					</view>
					<view class="charts-view-time-ops-content">
						<qiun-data-charts type="column" :opts="opts" :chartData="chartData" @getIndex="getIndex" />
					</view>
				</view>
			</view>
		</view>
	</view>
	<view class="times">
		<view>
			<u-datetime-picker :minDate="0" :maxDate="maxDate" @confirm="onOkTime" @cancel="onCloseTime"
				:show="showTime" v-model="value1" mode="date"></u-datetime-picker>
		</view>
	</view>
</template>

<script>
	import {
		BASE_IP
	} from '@/common/http/url.js'
	export default {
		name: "charts",
		data() {
			return {
				index: 0,
				showTime: false,
				value1: Number(new Date()),
				currentTimestamp: Date.now(), // 当前时间戳
				maxDate: null,
				endTime: "",
				startTime: "",
				chartData: {},
				//您可以通过修改 config-ucharts.js 文件中下标为 ['column'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
				opts: {
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [15, 15, 0, 5],
					enableScroll: false,
					legend: {},
					xAxis: {
						disableGrid: true
					},
					yAxis: {
						data: [{
							min: 0
						}]
					},
					extra: {
						column: {
							type: "group",
							width: 30,
							activeBgColor: "#000000",
							activeBgOpacity: 0.08
						}
					}
				},
				showPicker: false,
				unitColumns: [
					['消防一中队', '消防二中队', '消防三中队', '消防四中队']
				],
				unit: "",
				unitNames: [],
				units: []
			}
		},
		mounted() {
			// 获取当前日期
			const currentDate = new Date();
			// 获取当前日期的时间戳（毫秒）
			const currentTimestamp = currentDate.getTime();
			// 将当前日期的时间戳设置为日期选择器的最大可选择日期
			this.maxDate = currentTimestamp;
		},
		methods: {
			onOkTime(res) {
				this.showTime = false
				console.log(res.value)
				this.timeInData(res.value)
			},
			timeInData(time) {
				const timestamp = time;
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = date.getMonth() + 1;
				const day = date.getDate();
				const dateString = `${year}-${month}-${day}`;
				console.log(dateString); // 示例输出：1975-1-1
				this.endTime = dateString
			},
			onCloseTime() {
				this.showTime = false
			},
			getTime() {
				// 创建一个 Date 对象来获取当前日期
				const currentDate = new Date();
				// 获取当前日期的年、月、日
				const year = currentDate.getFullYear();
				const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
				const day = String(currentDate.getDate()).padStart(2, '0');
				// 构建日期字符串
				const formattedDate = `${year}-${month}-${day}`;
				this.endTime = formattedDate
			},
			getTimeBySeven() { // 获取过去七天的日期
				// 获取当前日期
				const currentDate = new Date();

				// 循环获取过去七天的日期
				for (let i = 0; i < 7; i++) {
					// 获取当前日期的年、月、日
					const year = currentDate.getFullYear();
					const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
					const day = String(currentDate.getDate()).padStart(2, '0');
					// 构建日期字符串
					const formattedDate = `${year}-${month}-${day}`;
					// 输出结果
					if (i == 6) {
						this.startTime = formattedDate
					}
					// 将当前日期减去一天
					currentDate.setDate(currentDate.getDate() - 1);
				}
			},
			getServerData() {
				//模拟从服务器获取数据时的延时

			},
			handleCustomClick(item) {
				// 处理自定义点击事件
				console.log('Custom click:', item);
				// 触发自定义事件
				this.$emit('custom-click', item);
			},
			getIndex(data) {
				// console.log(data)
			},
			showOpsUnit() {
				this.showPicker = true
			},
			onPickerConfirm: async function(res1) {
			    this.showPicker = false;
				uni.removeStorageSync("units")
				this.chartData = {}
			    this.unit = res1.value;
			    let url = BASE_IP + "pc/record/queryByUnit/" + res1.value + "/" + this.index;
			    // console.log(url);
			  
			    try {
			        const user = uni.getStorageSync("user");
			        const response = await new Promise((resolve, reject) => {
			            uni.request({
			                header: {
			                    "Authorization": user.token
			                },
			                method: "GET",
			                url: url,
			                success: (res) => {
								// console.log(res)
			                    resolve(res);
			                },
			                fail: (error) => {
								// console.log(error)
			                    reject(error);
			                }
			            });
			        });
			
			        if (response.statusCode === 200) {
			            // console.log(response);
			            uni.setStorageSync("units", response.data);
			        }
					if(response.statusCode == 500){
						uni.showModal({
							title:"提示",
							content:"当前单位未查询到此条目记录，请选择其它条目或者添加日志记录",
							success: (res) => {
								if(res.confirm){
								return	
								}
							},
							showCancel:false
						})
						return
					}
			        const units = uni.getStorageSync("units");
			        const res = {
			            categories: [],
			            series: []
			        };
			
			        const result = units;
			        // 遍历结果集，提取日期和记录人信息
			        result.forEach(item => {
			            const recordTime = new Date(item.recordTime);
			            const formattedDate =
			                `${recordTime.getFullYear()}-${(recordTime.getMonth() + 1).toString().padStart(2, '0')}-${recordTime.getDate().toString().padStart(2, '0')}`;
			            const name = item.name;
			
			            // 将日期添加到 categories 数组中
			            if (!res.categories.includes(formattedDate)) {
			                res.categories.push(formattedDate);
			            }
			
			            // 查找 series 中是否已存在该记录人，若存在则将索引添加到 seriesIndex 数组中，若不存在则创建新的记录人对象
			            const seriesIndex = [];
			            res.series.forEach((series, index) => {
			                if (series.name === `记录人：${name}`) {
			                    seriesIndex.push(index);
			                }
			            });
			
			            // 遍历 seriesIndex 数组，将对应日期的数据设置为1
			            seriesIndex.forEach(index => {
			                res.series[index].data[res.categories.indexOf(formattedDate)] = 1;
			            });
			
			            // 如果没有找到匹配的记录人，创建新的记录人对象，并将对应日期的数据设置为1
			            if (seriesIndex.length === 0) {
			                const newData = Array(res.categories.length).fill(0);
			                newData.push(1);
			                res.series.push({
			                    name: `记录人：${name}`,
			                    data: newData
			                });
			            }
			        });
			
			        // 检查结果集日期是否在最近七天内，不在的设置为0
			        res.series.forEach(series => {
			            for (let i = 0; i < res.categories.length; i++) {
			                const date = res.categories[i];
			                const dataIndex = series.data[i];
			                if (dataIndex !== 1 && result.some(item => item.recordTime.startsWith(date))) {
			                    series.data[i] = 1;
			                } else {
			                    series.data[i] = 0;
			                }
			            }
			        });
			
			        // 将结果转换为深拷贝的对象
			        this.chartData = JSON.parse(JSON.stringify(res));
			    } catch (error) {
			        console.error(error);
			    }
			},
			changePickerHandler(res) {
				// this.showPicker = false
				// console.log(res)
			},
			onClosePicker() {
				this.showPicker = false
			},
			getUnit() {
				let user = uni.getStorageSync("user")
				let url = BASE_IP + "pc/unit/getAll"
				uni.request({
					header: {
						"Authorization": user.token
					},
					method: "GET",
					url: url,
					success: (res) => {
						if (res.statusCode == 200) {
							uni.setStorageSync("units", res.data)
						}
					}
				})
				let units = uni.getStorageSync("units")
				this.units = units
				this.unitNames = []
				let temp = []
				for (let unit in units) {
					temp.push(units[unit].unitName)
				}
				this.unitNames.push(temp)
				uni.navigateTo({
					url: "/pages/index/index",
					success: (res) => {
						uni.navigateBack()
					}
				})
			},
		},
		onLoad(ops) {
			let time = setTimeout((res => {
				let mid = ops.mid
				if (mid == 1) {
					uni.setNavigationBarTitle({
						title: "防火检查记录"
					})
				}
				if (mid == 2) {
					uni.setNavigationBarTitle({
						title: "防火巡查记录"
					})
				}
				if (mid == 3) {
					uni.setNavigationBarTitle({
						title: "消防栓制室值班记录"
					})
				}
				this.index = mid
				this.getUnit()
				this.getTime()
				this.getTimeBySeven()
				this.getServerData()
			}), 500)

			let time1 = setTimeout((res => {
				let mid = ops.mid
				if (mid == 1) {
					uni.setNavigationBarTitle({
						title: "防火检查记录"
					})
				}
				if (mid == 2) {
					uni.setNavigationBarTitle({
						title: "防火巡查记录"
					})
				}
				if (mid == 3) {
					uni.setNavigationBarTitle({
						title: "消防栓制室值班记录"
					})
				}
				this.index = mid
				this.getUnit()
				this.getTime()
				this.getTimeBySeven()
				this.getServerData()
			}), 800)
		}
	}
</script>

<style>
	.charts-view-list {
		width: 100%;
		height: 100%;
		margin: auto;
		position: absolute;
		top: 0px;
	}

	.charts-view-time-ops {
		width: 90%;
		height: 100%;
		margin: 20rpx auto;
	}

	.charts-view-time-ops-son {
		width: 100%;
		display: flex;
		justify-content: space-between;
		height: 150rpx;
		font-size: 12px;
	}

	.charts-view-time-ops-content {
		width: 100%;
		height: 300px;

	}
</style>